<template>
  <view>
    <video id="video" :controls="false" :show-center-play-btn="false" :enable-progress-gesture="false" :muted="true">
      <cover-image v-if="photoType === 'portrait'" class="w569-h828 photograph"
        :src="baseImgUrl + '/camera/portrait.png'" />
      <cover-image v-else-if="photoType === 'emblem'" class="w569-h828 photograph"
        :src="baseImgUrl + '/camera/emblem.png'" />

      <cover-image v-else-if="photoType === 'photo'" class="photo photograph" :src="baseImgUrl + '/camera/photo.png'" />
    </video>

    <view class="bottom font-36-fff" :style="paddingBottom">
      <view class="wrap">
        <view class="btn" @click="btn_back">
          返回
        </view>
        <view class="take" @click="btn_takePhoto">
          <image class="w131-h131" :src="baseImgUrl + '/camera/shutter.png'">
          </image>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { baseApiUrl, baseImgUrl } from '@/config.js';
import { mapMutations } from 'vuex'
export default {
  data() {
    return {
      baseImgUrl: baseImgUrl,

      fileUrls: null, // 文件上传路径
      photoType: null,
      label: null,

      video: null, // 相机实例
      canvas: null, // 画布实例
      width: 375,
      height: 667,
    };
  },

  onLoad(optionflips) {
    this.photoType = optionflips.photoType
    this.label = optionflips.label

    this.width = window.innerWidth || 375;
    this.height = window.innerHeight || 667;
    // 启动相机
    this.init()
  },

  // onShow() {
  //   // 获取全局宽高
  //   const systemInfo = uni.getSystemInfoSync()
  //   this.windowHeight = systemInfo.windowHeight
  //   this.windowWidth = systemInfo.windowWidth
  // },
  methods: {
    ...mapMutations(['login', 'SETPHOTOCATCH']),
    async init() {
      let facingMode = this.photoType == 'emblem' || this.photoType == 'portrait' ? 'environment' : 'user'
      let videoStream = await navigator.mediaDevices.getUserMedia({
        video: {
          width: this.height,
          height: this.width,
          facingMode: facingMode // 前置摄像头，或使用 "environment" 表示后置摄像头
        },
        audio: false,
      });
      this.video = document.getElementsByTagName("video")[0];
      //挂在视频流
      this.$set(this.video, 'srcObject', videoStream)
      //设置播放
      this.video.play();

      // 创建canvas
      const canvas = document.createElement("canvas");
      canvas.width = this.width;
      canvas.height = this.height;
      canvas.style.display = "none";
      document.body.appendChild(canvas);
      this.canvas = canvas;
    },
    // 拍照
    btn_takePhoto() {
      uni.showLoading({
        title: '拍摄中'
      })
      this.takePhoto();
    },
    async takePhoto() {
      try {
        const ctx = this.canvas.getContext("2d");
        ctx.drawImage(this.video, 0, 0, this.width, this.height); // 必须调用draw方法来渲染canvas上的内容
        const base64Image = this.canvas.toDataURL("image/png"); // 获取 base64 编码的图片
        await this.uploadImage(base64Image)
        uni.hideLoading();
        ctx.clearRect(0, 0, this.width, this.height);
        this.btn_back()
      } catch (e) {
        console.log(e);
      }
    },
    // 上传图片
    uploadImage(url) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: baseApiUrl + "/common/upload",
          name: "file",
          header: {
            Authorization: this.$store.state.login.userInfo.token,
          },
          filePath: url,
          success: uploadFileRes => {
            this.fileUrls = JSON.parse(uploadFileRes.data).fileName
            // 将值存入store中
            let data = {
              key: this.label,
              url: this.fileUrls
            }
            this.SETPHOTOCATCH(data)
            resolve(true)
          },
          fail: err => {
            uni.showToast({
              title: err,
              icon: 'none',
              duration: 2000
            });
          }
        });
      })
    },
    // 返回
    btn_back() {
      uni.navigateBack()
    },
  },
  computed: {
    // 底部导航栏高度 单位px
    navigationBarHeight() {
      return uni.getStorageSync("menuInfo").navigationBarHeight || uni.getStorageSync("menuInfo").statusBarHeight / 2;
    },
    // 底部菜单padding掉导航栏的位置
    paddingBottom() {
      if (this.navigationBarHeight) {
        return "padding-bottom:" + this.navigationBarHeight + "px;";
      }
      else {
        return "";
      }
    }
  }
}
</script>

<style lang="less" scoped>
#video {
  width: 100vw;
  height: 100vh;
  position: absolute;
  z-index: 1;

  .photograph {
    position: relative;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}

.photo {
  width: 569rpx;
  height: 569rpx;
}

.bottom {
  width: 100%;
  background-color: #000;
  position: fixed;
  bottom: 0;
  z-index: 2;

  .wrap {
    padding: 0 80rpx;
    height: 160rpx;
    display: flex;
    align-items: center;
    justify-content: flex-start;

    .btn {
      width: 33.3%;
      display: flex;
      justify-content: flex-start;
    }

    .take {
      width: 33.3%;
      display: flex;
      justify-content: center;
    }
  }
}

.w569-h828 {
  width: 569rpx;
  height: 828rpx;
}

.w131-h131 {
  width: 100rpx;
  height: 100rpx;
}

.font-36-fff {
  font-size: 36rpx;
  color: #fff;
}

.menu-flip {
  width: 100rpx;
}

::v-deep .uni-video-video {
  object-fit: cover !important;
}
</style>
